package servlet.user;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@WebServlet("/code")
public class Code extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建空白图片
        BufferedImage image = new BufferedImage(80, 25, BufferedImage.TYPE_INT_RGB);
        //1.获取图片画笔
        Graphics g = image.getGraphics();
        Random r = new Random();
        //2.设置画笔颜色
        //设置背景颜色
        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
        g.fillRect(0, 0, 80, 25);
        //4.调用自定义的方法，获取长度为5的字母数字组合的字符串
        String number = getNumber(5);
        System.out.println(number);
        req.getSession().setAttribute("code",number);
        g.setColor(new Color(0, 0, 0));
        g.setFont(new Font(null, Font.BOLD, 20));
        g.drawString(number, 5, 20);
        for (int i = 0; i < 8; i++) {
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            g.drawLine(r.nextInt(80), r.nextInt(20), r.nextInt(80), r.nextInt(20));
        }
        resp.setContentType("image/ jpeg");
        OutputStream ops =resp.getOutputStream();
        ImageIO.write(image,"jpeg",ops);
        ops.close();
    }


    private String getNumber(int size) {
        String str = "ABCDEFGHJKLMNPQRSTUVWXYZ0123456789";
        String number = "";
        Random r = new Random();
        for (int i = 0; i < size; i++) {
            number += str.charAt(r.nextInt(str.length()));
        }
        return number;

    }
}
